package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {

    private ServerSocket serverSocket = null;

    public TcpEchoServer(int Port) throws IOException {
        serverSocket = new ServerSocket(Port);
    }

    public void start() throws IOException {
        // 创建一个线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        System.out.println("服务器启动！");
        while (true){
            //  accept的含义 接收一个连接（来自客户端的连接）
            Socket clientSocket = serverSocket.accept();
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d]客户端上线！",clientSocket.getInetAddress().toString(),clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            // 字节流转换为字符流
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true){
                if(!scanner.hasNext()){
                    System.out.println();
                    System.out.println("客户端已下线！");
                    break;
                }
                //读取数据
                String request = scanner.next();
                //计算响应
                String response= process(request);
                //返回响应
                printWriter.println(response);
                printWriter.flush();
                System.out.println();
                System.out.printf("[%s:%d] request: %s   response:  %s",clientSocket.getInetAddress().toString(),clientSocket.getPort(),request,response);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            clientSocket.close();
        }


    }

    private String process(String request) {
        return request;
    }


    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
